﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Caching;
using System.Linq.Expressions;

namespace Framework.Zhaogang.Cache.Core
{
    /// <summary>
    /// 本地缓存管理器
    /// </summary>
    public class LocalCacheManager : ICacheManager
    {
        /// <summary>
        /// 缓存区域名称
        /// </summary>
        public string RegionName { get; private set; }
        private ObjectCache cache;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="regionName">缓存区域名称</param>
        public LocalCacheManager(string regionName)
        {
            RegionName = regionName;
            cache = MemoryCache.Default;
        }

        /// <summary>
        /// 覆盖
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="isAbsoluteExpire"></param>
        /// <param name="expireMinutes"></param>
        public bool Set(string key, object value, bool isAbsoluteExpire = true, int expireMinutes = 0)
        {
            var cacheItem = new CacheItem(MergeKey(key), value);
            var cacheItemPolicy = new CacheItemPolicy();

            if (expireMinutes > 0)
            {
                if (isAbsoluteExpire)
                {
                    cacheItemPolicy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(expireMinutes);
                }
                else
                {
                    cacheItemPolicy.SlidingExpiration = TimeSpan.FromMinutes(expireMinutes);
                }
            }

            cache.Set(cacheItem, cacheItemPolicy);
            return true;
        }

        /// <summary>
        /// 移除
        /// </summary>
        /// <param name="key"></param>
        /// <returns>被移除的对象</returns>
        public object Remove(string key)
        {
            return cache.Remove(MergeKey(key));
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public T Get<T>(string key)
        {
            return (T)Convert.ChangeType(cache.Get(MergeKey(key)), typeof(T));
        }

        /// <summary>
        /// 是否存在键
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool HasKey(string key)
        {
            return cache.Contains(MergeKey(key));
        }

        /// <summary>
        /// 根据条件模糊查询（慎用）
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="expression"></param>
        /// <param name="keyParam"></param>
        /// <returns></returns>
        public IEnumerable<T> Where<T>(Func<T, bool> expression, string keyParam = "")
        {
            var cacheItems = string.IsNullOrWhiteSpace(keyParam) ? cache.Where(k => k.Key.StartsWith(RegionName + "_")) : cache.Where(k => k.Key.StartsWith(RegionName + "_") && k.Key.Contains(keyParam));
            return cacheItems == null ? new List<T>() : cacheItems.Select(k => (T)k.Value).Where(expression);
        }

        /// <summary>
        /// 合并键
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        private string MergeKey(string key)
        {
            return RegionName + "_" + key;
        }
    }
}
